package io.zbus.data.spider;

import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.jsoup.nodes.Document;

import io.zbus.kit.FileKit;
import io.zbus.kit.JsKit; 
  
public class JsParser {  
	ScriptEngineManager factory = new ScriptEngineManager();
	ScriptEngine engine = factory.getEngineByName("javascript");   
	private FileKit fileKit = new FileKit(false);    
	
	public Object parse(Document doc, String jsFileName, Map<String, Object> context) throws Exception {  
		String js = fileKit.loadFile(jsFileName);    
		engine.eval(js);
		Invocable inv = (Invocable) engine; 
		final Object res = inv.invokeFunction("main", doc, context);  
		return JsKit.convert(res);
	}
	
	public void setCacheEnabled(boolean cacheEnabed) {
		fileKit.setCacheEnabled(cacheEnabed);
	}  
} 